package com.chenyi.web.controller.common;

import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.constant.Constants;
import com.chenyi.common.core.redis.RedisCache;
import com.chenyi.common.utils.sign.Base64;
import com.chenyi.common.utils.uuid.IdUtils;
import com.google.common.collect.Maps;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author wangkh
 */
@RestController
public class CaptchaController
{
    @Autowired
    private RedisCache redisCache;
    
    // 验证码类型
    @Value("${chenyi.captchaType}")
    private String captchaType;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public ResponseEntity<Object> getCode(HttpServletResponse response) throws IOException
    {
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;


        SpecCaptcha specCaptcha = new SpecCaptcha(111, 36);
        // 设置字体
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);

        redisCache.setCacheObject(verifyKey, specCaptcha.text(), Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream stream = new FastByteArrayOutputStream();
        specCaptcha.out(stream);

        Map<String,Object> data = Maps.newHashMap();
        data.put("uuid", uuid);
        data.put("img", Base64.encode(stream.toByteArray()));
        return ResponseEntity.ok(data);
    }
}
